package com.ruoyi.dynamic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.pojo.result.PageUtils;
import com.ruoyi.common.core.pojo.result.Pages;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.dynamic.mapper.RoomProgramMapper;
import com.ruoyi.dynamic.model.constant.DynamicConstant;
import com.ruoyi.dynamic.model.constant.RoomChatRoomKvConstant;
import com.ruoyi.dynamic.model.pojo.entity.Room;
import com.ruoyi.dynamic.model.pojo.entity.RoomProgram;
import com.ruoyi.dynamic.model.pojo.entity.RoomProgramRecord;
import com.ruoyi.dynamic.model.pojo.request.app.*;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomProgramInfoResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomProgramResult;
import com.ruoyi.dynamic.model.pojo.result.app.AppRoomSetResult;
import com.ruoyi.dynamic.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * <p>
 * 房间节目单 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-12-03
 */
@Service
public class RoomProgramServiceImpl extends ServiceImpl<RoomProgramMapper, RoomProgram> implements IRoomProgramService {

    @Autowired
    private IRoomProgramRecordService iRoomProgramRecordService;
    @Autowired
    private IRoomService iRoomService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private IRoomSetService iRoomSetService;


    @Override
    public Pages<AppRoomProgramInfoResult> programList(AppRoomSingSearchRequest pageSearchParam, Long userId) {
        Page<RoomProgram> roomProgramPage = PageUtils.initPage(pageSearchParam, RoomProgram.class);

        Page<RoomProgram> page = lambdaQuery()
                .eq(!CommonUtils.isNull(pageSearchParam.getRoomId()), RoomProgram::getRoomId, pageSearchParam.getRoomId())
                .orderByAsc(RoomProgram::getCreateTime)
                .page(roomProgramPage);

        List<AppRoomProgramInfoResult> collect = page.getRecords().stream().map(res -> {
            return AppRoomProgramInfoResult.builder()
                    .id(res.getId())
                    .roomId(res.getRoomId())
                    .userId(res.getUserId())
                    .heatCount(iRoomProgramRecordService.countHeat(res.getId()))
                    .isLook(iRoomProgramRecordService.countHeat(res.getId(), userId))
                    .name(res.getName())
                    .status(res.getStatus())
                    .build();
        }).collect(Collectors.toList());

        return PageUtils.pages(page, collect);
    }

    @Override
    public boolean addOrEdit(AppRoomProgarmAddOrEditRequest request) {
        Room verify = iRoomService.verify(request.getRoomId());
        RoomProgram program = getById(request.getId());
        if (CommonUtils.isNull(program)) {
            program = new RoomProgram();
        }
        program.setName(request.getName());
        program.setRoomId(request.getRoomId());
        program.setStatus(DynamicConstant.CheckStatus.YES);
        program.setUserId(SecurityContextHolder.getUserId());
        program.setCreateTime(new Date());
        return saveOrUpdate(program);
    }

    @Override
    public boolean removeProgram(AppRoomSingDelRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        return removeById(request.getId());
    }

    @Override
    public boolean startProgram(AppRoomWishCloseRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        AppRoomSetResult set = iRoomSetService.getUserRoomSet(verify.getUserId());
        Assert.isTrue(StringUtils.isNotBlank(set.getProgramContent()), "节目单描述为空");

        List<RoomProgram> list = lambdaQuery().eq(RoomProgram::getRoomId, request.getRoomId())
                .eq(RoomProgram::getStatus, DynamicConstant.CheckStatus.YES)
                .list();
        Assert.notEmpty(list, "当前无节目单无法开启");

        AppRoomProgramResult build = AppRoomProgramResult.builder()
                .number(list.size())
                .status(DynamicConstant.CheckStatus.YES)
                .programContent(set.getProgramContent())
                .build();
        iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_PROGRAM_INFO, JSONObject.toJSONString(build), 0, "", "");
        return true;
    }

    @Override
    public boolean wantLook(AppRoomSingDelRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        RoomProgram program = verify(request.getId());

        Long count = iRoomProgramRecordService
                .lambdaQuery().eq(RoomProgramRecord::getRoomId, request.getRoomId())
                .eq(RoomProgramRecord::getUserId, userId)
                .eq(RoomProgramRecord::getRoomProgramId, request.getId())
                .count();
        Assert.isTrue(count == 0, "请勿重复点击");

        RoomProgramRecord record = new RoomProgramRecord();
        record.setRoomId(request.getRoomId());
        record.setRoomProgramId(request.getId());
        record.setUserId(userId);
        record.setCreateTime(new Date());
        return iRoomProgramRecordService.save(record);
    }

    @Override
    public RoomProgram verify(Long id) {
        Optional<RoomProgram> roomProgram = lambdaQuery()
                .eq(RoomProgram::getId, id)
                .oneOpt();
        Assert.isTrue(roomProgram.isPresent(), "此记录不存在");
        return roomProgram.get();
    }

    @Override
    public boolean stopProgram(AppRoomWishCloseRequest request, Long userId) {
        Room verify = iRoomService.verify(request.getRoomId());
        AppRoomProgramResult build = AppRoomProgramResult.builder()
                .number(0)
                .status(DynamicConstant.CheckStatus.NO).build();
        iMessageService.setRoomChatRoomAttr(verify.getGroupId(), verify.getUserId().toString(), RoomChatRoomKvConstant.ROOM_PROGRAM_INFO, JSONObject.toJSONString(build), 0, "", "");

        iRoomProgramRecordService.lambdaUpdate()
                .eq(RoomProgramRecord::getRoomId, verify.getId()).remove();
        return true;
    }
}
